package com.nengchuan.kbms.dfs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.common.AutoWrapper;
import com.nengchuan.kbms.common.PageServiceImpl;
import com.nengchuan.kbms.dfs.dao.PermissionFileMapper;
import com.nengchuan.kbms.dfs.entity.dto.PermissionFileDTO;
import com.nengchuan.kbms.dfs.entity.po.PermissionFile;
import com.nengchuan.kbms.dfs.entity.vo.PermissionFileListVO;
import com.nengchuan.util.MapperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * t_permission_file（文件权限） 服务实现类
 * </p>
 *
 * @author abe
 * @since 2020-04-09
 */
@Service
public class PermissionFileServiceImpl extends PageServiceImpl<PermissionFileMapper, PermissionFile> implements PermissionFileService {

    /**
     * 保存用户设置的权限
     * 1. t_permission_file 数据入库 （数据存在的话忽略
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long savePermission(PermissionFileDTO dto) {
        Objects.requireNonNull(dto);

        PermissionFile permissionFile = getOne(new AutoWrapper<>(dto), false);
        if (permissionFile != null) {
            throw new NcException("保存失败，成员已设置权限");
        }
        permissionFile = insert(dto);
        return permissionFile.getId();
    }

    @Override
    public Boolean updatePermission(PermissionFileDTO dto) {
        Objects.requireNonNull(dto);
        Objects.requireNonNull(dto.getId(), "主键id不能为空");

        PermissionFile permissionFile = getOne(new AutoWrapper<>(dto), false);
        if (permissionFile == null || permissionFile.getId() == dto.getId()) {
            // 允许修改
            return update(dto);
        } else {
            throw new NcException("修改失败，成员已设置权限");
        }
    }

    /**
     * 文件权限列表
     * @param id 文件（文件夹）id
     * @return
     */
    @Override
    public List<PermissionFileListVO> list(Long id) {
        Objects.requireNonNull(id, "文件（夹）id不能为空");

        QueryWrapper<PermissionFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PermissionFile::getBizId, id);
        List<PermissionFile> permissionFileList = list(wrapper);
        return permissionFileList.stream().map(permissionFile -> {
            PermissionFileListVO vo = MapperUtils.mapping(permissionFile, PermissionFileListVO.class);
            // TODO 通过 permissionCode 设置权限概要内容
            vo.setSummary("暂无");
            return vo;
        }).collect(Collectors.toList());
    }

}
